CODE 27. Construct Binary Tree from Inorder and Postorder Traversal

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/09/20/2013-09-20-CODE 27 Construct Binary Tree from Inorder and Postorder Traversal/

访问原文「CODE 27. Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public TreeNode buildTree(int[] inorder, int[] postorder) {
// Start typing your Java solution below
// DO NOT write main() function
if (null == inorder || null == postorder || inorder.length <= 0
|| postorder.length <= 0) {
return null;
}
return dfs(inorder, postorder, 0, inorder.length - 1, 0,
postorder.length - 1);
}
TreeNode dfs(int[] inorder, int[] postorder, int inorderStart,
int inorderEnd, int postorderStart, int postorderEnd) {
TreeNode node = new TreeNode(postorder[postorderEnd]);
int nodeIndexInInorder = findElement(inorder, postorder[postorderEnd]);
int leftLength = nodeIndexInInorder - inorderStart;
int rightLength = inorderEnd - nodeIndexInInorder;
if (leftLength > 0) {
TreeNode left = dfs(inorder, postorder, inorderStart,
nodeIndexInInorder - 1, postorderStart, postorderEnd
- rightLength - 1);
node.left = left;
}
if (rightLength > 0) {
TreeNode right = dfs(inorder, postorder, nodeIndexInInorder + 1,
inorderEnd, postorderEnd - rightLength, postorderEnd - 1);
node.right = right;
}
return node;
}
int findElement(int[] array, int element) {
for (int i = 0; i < array.length; i++) {
if (array[i] == element) {
return i;
}
}
return -1;
}
Jerky Lu wechat
欢迎加入微信公众号